package com.jrzh.mvc.service.sys.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.jrzh.bean.CheckResultBean;
import com.jrzh.common.exception.ProjectException;
import com.jrzh.common.tools.CollectionTools;
import com.jrzh.common.utils.AESUtil;
import com.jrzh.common.utils.HttpClientHelper;
import com.jrzh.common.utils.ReflectUtils;
import com.jrzh.framework.base.convert.BaseConvertI;
import com.jrzh.framework.base.repository.BaseRepository;
import com.jrzh.framework.base.service.impl.BaseServiceImpl;
import com.jrzh.framework.bean.SessionUser;
import com.jrzh.mvc.constants.SysConstant;
import com.jrzh.mvc.convert.sys.ManegeInfoConvert;
import com.jrzh.mvc.convert.sys.ResourcesConvert;
import com.jrzh.mvc.model.sys.ManegeInfoModel;
import com.jrzh.mvc.model.sys.ResourcesModel;
import com.jrzh.mvc.model.sys.UserModel;
import com.jrzh.mvc.repository.sys.ManegeInfoRepository;
import com.jrzh.mvc.search.sys.ManegeInfoSearch;
import com.jrzh.mvc.search.sys.ResourcesSearch;
import com.jrzh.mvc.search.sys.UserSearch;
import com.jrzh.mvc.service.sys.ManegeInfoServiceI;
import com.jrzh.mvc.service.sys.manage.SysServiceManage;
import com.jrzh.mvc.view.sys.ManegeInfoView;
import com.jrzh.mvc.view.sys.ResourcesView;

@Service("manegeInfoService")
public class ManegeInfoServiceImpl extends BaseServiceImpl<ManegeInfoModel, ManegeInfoSearch, ManegeInfoView>
		implements ManegeInfoServiceI {

	@Autowired
	SysServiceManage sysServiceManage;

	@Autowired
	private ManegeInfoRepository manegeInfoRepository;

	@Autowired
	ResourcesConvert resourcesConvert;

	@Override
	public BaseRepository<ManegeInfoModel, Serializable> getDao() {
		return manegeInfoRepository;
	}

	@Override
	public BaseConvertI<ManegeInfoModel, ManegeInfoView> getConvert() {
		return new ManegeInfoConvert();
	}

	@Override
	@SuppressWarnings({ "unchecked", "rawtypes", "static-access" })
	public Boolean checkStatus(SessionUser sessionUser, UserModel user) throws ProjectException {

		Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
		Map<String, Object> param = new HashMap<String, Object>();
		try {
			List<ManegeInfoModel> list = sysServiceManage.manegeInfoService.findAll();
			boolean isLogin = true;
			ManegeInfoModel sysInfo = new ManegeInfoModel();
			if (CollectionTools.isBlank(list)) {
				isLogin = false;
				log.info("系统尚未初始化");
				param.put("sysUser", "默认用户");
				param.put("systemName", "默认系统");
				param.put("sysCode", "");
				sysInfo.setSysName("默认系统");
				sysInfo.setSysOwner("默认用户");
			} else {
				sysInfo = list.get(0);
				param.put("sysUser", sysInfo.getSysOwner());
				param.put("systemName", sysInfo.getSysName());
				param.put("sysCode", sysInfo.getSysCode());
			}
			param.put("adminUserNum", sysServiceManage.userService.count(new UserSearch()) + "");
			param.put("timestamp", Calendar.getInstance().getTimeInMillis() / 1000 + "");
			param.put("sign", HttpClientHelper.getSign(SysConstant.MIYAO, param));
			String data = HttpClientHelper.postBody(SysConstant.SYSTEM_MANAGER + "system/",
					AESUtil.encrypt(gson.toJson(param), SysConstant.MIYAO), "UTF-8");
			// aes解密
			data = AESUtil.decrypt(data, SysConstant.MIYAO);
			data = gson.toJson(data).replace("\\", "");
			data = data.substring(1, data.length() - 1);
			Map<String, String> dataMap = gson.fromJson(data, Map.class);
			CheckResultBean info = new CheckResultBean();
			info = (CheckResultBean) ReflectUtils.mapToObject1(dataMap, CheckResultBean.class);
			boolean flag = false;
			//String sysId = sysInfo.getId();
			// 返回的信息保存起来
			ManegeInfoModel sysInfo01 = new ManegeInfoConvert().editSysInfo(sysInfo, info);
			sessionUser = new SessionUser();
			sessionUser.setCode("superAdmin");
			sessionUser.setCode("超级管理员");
			if (!isLogin) {
				sysServiceManage.manegeInfoService.add(sysInfo, sessionUser);
			}else{
				sysInfo.setSysOwner(sysInfo01.getSysOwner());
				sysInfo.setSysName(sysInfo01.getSysName());
				sysInfo.setSysCode(sysInfo01.getSysCode());;
				sysInfo.setChargeType(sysInfo01.getChargeType());
				sysInfo.setEndTime(sysInfo01.getEndTime());
				sysServiceManage.manegeInfoService.edit(sysInfo, sessionUser);
			}
			flag = StringUtils.equals(sysInfo.getStatus(), "1") ? true : false;
			if (!flag)
			return false;
			JSONObject param1 = new JSONObject(true);
			List<Map> users = new ArrayList<Map>();
			Map<String, Object> param2 = new HashMap<String, Object>();
			param2.put("code", user.getCode() + "");
			param2.put("email", user.getEmail() + "");
			param2.put("tels", user.getTel() + "");
			param2.put("remark", user.getRemark() + "");
			users.add(param2);
			param1.put("sysCode", sysInfo.getSysCode());
			param1.put("loginCode", user.getCode());
			param1.put("UserList", users);
			param1.put("timestamp", Calendar.getInstance().getTimeInMillis() / 1000 + "");
			param1.put("sign", HttpClientHelper.getSign(SysConstant.MIYAO, param1));
			data = HttpClientHelper.postBody(SysConstant.SYSTEM_MANAGER + "checkUser/",
					AESUtil.encrypt(gson.toJson(param1), SysConstant.MIYAO), "UTF-8");
			// aes解密
			data = AESUtil.decrypt(data, SysConstant.MIYAO);
			data = gson.toJson(data).replace("\\", "");
			data = data.substring(1, data.length() - 1);
			dataMap = gson.fromJson(data, Map.class);
			info = new CheckResultBean();

			info = (CheckResultBean) ReflectUtils.mapToObject1(dataMap, CheckResultBean.class);
			
			//log.info("用户登陆到期时间为："+info.getEndTime());
			
			user.setEndTime(info.getEndTime());
			
			sysServiceManage.userService.edit(user, sessionUser.getSystemUser());
			
			//log.info("權限查詢響應==info==" + info.toString());

			flag = StringUtils.equals(info.getStatus(), "1") ? true : false;

			//log.info("====结束校驗登錄用戶權限====");

			if (!flag)
				return false;

			//log.info("=====开始模块权限校验=====");

			// 模块权限管理
			List<ResourcesModel> modelList = new ArrayList<ResourcesModel>();
			List<ResourcesView> resourceList = new ArrayList<ResourcesView>();

			ResourcesSearch search = new ResourcesSearch();
			search.setEqLevel(1);
			modelList = sysServiceManage.resourcesService.list(search);

			Map<String, Object> map = new HashMap<String, Object>();
			map.put("lang", "zh");
			sessionUser = sessionUser.getSystemUser();
			sessionUser.setAttrs(map);

			resourceList = resourcesConvert.convertToViewListI18n(modelList, sessionUser);

			param1 = new JSONObject(true);

			users = new ArrayList<Map>();

			for (int i = 0; i < modelList.size(); i++) {

				param2 = new HashMap<String, Object>();

				param2.put("key", modelList.get(i).getName() + "");
				param2.put("name", resourceList.get(i).getName() + "");

				users.add(param2);

			}

			param1.put("sysCode", sysInfo.getSysCode());

			param1.put("ModelList", users);

			param1.put("timestamp", Calendar.getInstance().getTimeInMillis() / 1000 + "");
			param1.put("sign", HttpClientHelper.getSign(SysConstant.MIYAO, param1));
			data = HttpClientHelper.postBody(SysConstant.SYSTEM_MANAGER + "checkModels/",
					AESUtil.encrypt(gson.toJson(param1), SysConstant.MIYAO), "UTF-8");
			// aes解密
			data = AESUtil.decrypt(data, SysConstant.MIYAO);
			data = gson.toJson(data).replace("\\", "");
			data = data.substring(1, data.length() - 1);
			dataMap = gson.fromJson(data, Map.class);
			info = new CheckResultBean();
			info = (CheckResultBean) ReflectUtils.mapToObject1(dataMap, CheckResultBean.class);
			flag = StringUtils.equals(info.getStatus(), "1") ? true : false;
			return flag;
		} catch (Exception e1) {
			log.info("权限检验错误");
			e1.printStackTrace();
			throw new ProjectException(e1.getMessage());
		}

	}

}
